package cn.jiyun.service.impl;

import cn.jiyun.mapper.CampusMapper;
import cn.jiyun.mapper.MajorMapper;
import cn.jiyun.pojo.Campus;
import cn.jiyun.pojo.Major;
import cn.jiyun.res.JsonRes;
import cn.jiyun.service.CampusService;
import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;
import java.util.List;

@Service
public class CampusServiceImpl implements CampusService {
    @Autowired
    CampusMapper campusMapper;
    @Autowired
    MajorMapper majorMapper;
    @Override
    public PageInfo findPage(Integer pageNum, Integer pageSize, Campus campus) {
        PageHelper.startPage(pageNum,pageSize);
        QueryWrapper<Campus> qw = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(campus.getName())){
            qw.like("name",campus.getName());

        }
        List<Campus> list=campusMapper.selectList(qw);
        return new PageInfo(list);
    }

    @Override
    public JsonRes addCampus(Campus campus) {
        QueryWrapper<Campus> qw = new QueryWrapper<>();
        qw.eq("name",campus.getName());
        Campus campus1 = campusMapper.selectOne(qw);
        if (campus1==null){
            campusMapper.insert(campus);
            return JsonRes.res(0,"添加成功");
        }
        else {
            return JsonRes.res(1,"不能添加重复的校区");
        }
    }

    @Override
    public JsonRes updateCampus(Campus campus) {
        campusMapper.updateById(campus);
        return JsonRes.res(0,"修改成功");
    }

    @Override
    public JsonRes delMany(Integer[] ids) {
        QueryWrapper<Major> qw = new QueryWrapper<>();
            qw.in("cid",Arrays.asList(ids));
            List<Major> major = majorMapper.selectList(qw);
            if (major.isEmpty()){
                campusMapper.deleteBatchIds(Arrays.asList(ids));
                return JsonRes.res(0,"删除成功");
            }
            else {
                return JsonRes.res(1,"该校区下有专业不能被删除");
        }


    }

    @Override
    public List<Campus> findAll() {
        return campusMapper.selectList(null);
    }
}
